package com.wz.project.system.item.controlle;

import com.wz.common.utils.poi.ExcelUtil;
import com.wz.common.utils.security.ShiroUtils;
import com.wz.framework.aspectj.lang.annotation.Log;
import com.wz.framework.aspectj.lang.enums.BusinessType;
import com.wz.framework.web.controller.BaseController;
import com.wz.framework.web.domain.AjaxResult;
import com.wz.project.system.dayReport.entity.DayReport;
import com.wz.project.system.dayReport.repository.DayReportDao;
import com.wz.project.system.item.domain.Item;
import com.wz.project.system.item.domain.ItemDetail;
import com.wz.project.system.item.domain.ItemDetails;
import com.wz.project.system.item.domain.ItemDetailss;
import com.wz.project.system.item.service.ItemService;
import com.wz.project.system.post.service.IPostService;
import com.wz.project.system.prjgroup.domain.Prjgroup;
import com.wz.project.system.prjgroup.service.PrjGroupService;
import com.wz.project.system.role.domain.Role;
import com.wz.project.system.role.service.IRoleService;
import com.wz.project.system.user.domain.User;
import com.wz.project.system.user.service.IUserService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/system/item")
public class ItemController extends BaseController {
    private String prefix = "system/item";

    @Autowired
    private IUserService userService;

    @Autowired
    private ItemService itemService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPostService postService;

    @Autowired
    private DayReportDao dayReportDao;

    @Autowired
    private PrjGroupService prjGroupService;
    @RequiresPermissions("system:item:view")
    @GetMapping()
    public String user()
    {
        return prefix + "/item";
    }

//    @RequiresPermissions("system:item:list")
    @PostMapping("/list")
    @ResponseBody
    public Object list(ItemDetails itemDetails) {
        //单表查询可以用分页插件，多表最好不要用
        startPage();
        List<ItemDetails> list=itemService.selectItemDetailsList(itemDetails);
        return getDataTable(list);
    }

    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @RequiresPermissions("system:user:export")
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(User user)
    {
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @RequiresPermissions("system:user:import")
    @PostMapping("/importData")
    @ResponseBody
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        List<User> userList = util.importExcel(file.getInputStream());
        String message = userService.importUser(userList, updateSupport);
        return AjaxResult.success(message);
    }

    @RequiresPermissions("system:user:view")
    @GetMapping("/importTemplate")
    @ResponseBody
    public AjaxResult importTemplate()
    {
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        return util.importTemplateExcel("用户数据");
    }


    /**
     * 新增项目
     */
    @GetMapping("/add")
    public String add(ModelMap mmap)
    {
        /*mmap.put("roles", roleService.selectRoleAll().stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        mmap.put("posts", postService.selectPostAll());*/
        return prefix + "/add";
    }

    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(Item item)
    {
        item.setTheProblem("无");
        String s = String.valueOf(System.currentTimeMillis());
        String substring = s.substring(s.length() - 6);
        int pejId = Integer.parseInt(substring);
        item.setPrjID(pejId);
        return toAjax(itemService.insertItem(item));
    }

    /**
     * 项目详情
     */
    @GetMapping("/detail/{prjgroupId}")
    public String detalis(@PathVariable("prjgroupId") Integer prjgroupId, ModelMap mmap)
    {

        ItemDetail ItemDetail= itemService.selectUserGroupByPrjld(prjgroupId);
        SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String transformDate=simpleDateFormat.format(ItemDetail.getFromDate());
        ItemDetail.setFromDate(transformDate);
        mmap.put("prjDetail", ItemDetail);
        return prefix + "/detail";
    }
    /**
     * 项目人员
     */
    @GetMapping("/details/{prjID}")
    public ModelAndView detali(@PathVariable("prjID") Integer prjID, ModelMap mmap) throws ParseException {


        List<ItemDetailss> itemDetailsses = itemService.selectDetailByPrjld(Integer.valueOf(prjID));
        ArrayList<ItemDetailss> itemDetailssess  = new ArrayList<>();
        for (ItemDetailss itemDetailss : itemDetailsses) {
            DayReport topByStaffName = dayReportDao.findTopByStaffName(itemDetailss.getName());
            if (topByStaffName!=null){
                itemDetailss.setTodayPlan(topByStaffName.getTodayPlan());
                itemDetailss.setStaffStatus(topByStaffName.getStaffStatus());
                itemDetailss.setNotDoWork(topByStaffName.getNotDoWork());
            }
            itemDetailssess.add(itemDetailss);
        }
        Integer prjgroupId = itemDetailsses.get(0).getPrjgroupId();
        Prjgroup prjgroup = prjGroupService.selectOneById(prjgroupId);
        mmap.put("item",prjgroup);
        mmap.put("prjDetail", itemDetailssess);
        return new ModelAndView(prefix + "/details");
    }

    /**
     * 修改项目
     * @param prjID
     * @param mmap
     * @return
     */
    @GetMapping("/edit/{prjID}")
    public String edit(@PathVariable("prjID") Integer prjID, ModelMap mmap)
    {
        Item item=itemService.selectItemByItemPrjID(prjID);

        /*SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        String transformDate=simpleDateFormat.format(item.getFromDate());
        item.setFromDate(transformDate);*/
       /* String fromDate = DateUtils.parseDateToStr("yyyy-MM-dd", item.getFromDate());
        item.setFromDates(fromDate);*/

        List<Prjgroup> prjgroups = prjGroupService.selectPrjgroupByDeptId(item.getDeptId());
        mmap.put("item", item);
        mmap.put("prjgroups",prjgroups);
        return prefix + "/edit";
    }

    /**
     * form-user-edit
     * 修改保存项目
     */
    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:item:saveAndUpdate")
    @PostMapping("/saveAndUpdate")
    @ResponseBody
    public AjaxResult saveAndUpdate(@Validated Item item)
    {

        return toAjax(itemService.saveAndUpdate(item));
    }


    /**
     * 修改保存用户
     */
    @RequiresPermissions("system:user:resetPwd")
    @GetMapping("/resetPwd/{userId}")
    public String resetPwd(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        mmap.put("user", userService.selectUserById(userId));
        return prefix + "/resetPwd";
    }

    @RequiresPermissions("system:user:resetPwd")
    @Log(title = "重置密码", businessType = BusinessType.UPDATE)
    @PostMapping("/resetPwd")
    @ResponseBody
    public AjaxResult resetPwdSave(User user)
    {
        userService.checkUserAllowed(user);
        if (userService.resetUserPwd(user) > 0)
        {
            if (ShiroUtils.getUserId().longValue() == user.getUserId().longValue())
            {
                setSysUser(userService.selectUserById(user.getUserId()));
            }
            return success();
        }
        return error();
    }

    /**
     * 进入授权角色页
     */
    @GetMapping("/authRole/{userId}")
    public String authRole(@PathVariable("userId") Long userId, ModelMap mmap)
    {
        User user = userService.selectUserById(userId);
        // 获取用户所属的角色列表
        List<Role> roles = roleService.selectRolesByUserId(userId);
        mmap.put("user", user);
        mmap.put("roles", User.isAdmin(userId) ? roles : roles.stream().filter(r -> !r.isAdmin()).collect(Collectors.toList()));
        return prefix + "/authRole";
    }

    /**
     * 用户授权角色
     */
    @RequiresPermissions("system:user:add")
    @Log(title = "用户管理", businessType = BusinessType.GRANT)
    @PostMapping("/authRole/insertAuthRole")
    @ResponseBody
    public AjaxResult insertAuthRole(Long userId, Long[] roleIds)
    {
        userService.insertUserAuth(userId, roleIds);
        return success();
    }

    @RequiresPermissions("system:item:remove")
    @Log(title = "项目管理", businessType = BusinessType.DELETE)
    @PostMapping("/remove")
    @ResponseBody
    /*public AjaxResult remove(String ids)
    {
        return toAjax(userService.deleteUserByIds(ids));
    }*/

    public AjaxResult remove(Integer ids)
    {
        return toAjax(itemService.deleteItemByIds(ids));
    }

    /**
     * 校验用户名
     */
    @PostMapping("/checkLoginNameUnique")
    @ResponseBody
    public String checkLoginNameUnique(User user)
    {
        return userService.checkLoginNameUnique(user.getLoginName());
    }

    /**
     * 校验手机号码
     */
    @PostMapping("/checkPhoneUnique")
    @ResponseBody
    public String checkPhoneUnique(User user)
    {
        return userService.checkPhoneUnique(user);
    }

    /**
     * 校验email邮箱
     */
    @PostMapping("/checkEmailUnique")
    @ResponseBody
    public String checkEmailUnique(User user)
    {
        return userService.checkEmailUnique(user);
    }

    /**
     * 用户状态修改
     */
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @RequiresPermissions("system:user:edit")
    @PostMapping("/changeStatus")
    @ResponseBody
    public AjaxResult changeStatus(User user)
    {
        userService.checkUserAllowed(user);
        return toAjax(userService.changeStatus(user));
    }

    @RequestMapping("selectPrjgroupByDeptId/{deptId}")
    @ResponseBody
    public List<Prjgroup> selectPrjgroupByDeptId(@PathVariable Integer deptId)
    {
        List<Prjgroup> prjgroups=prjGroupService.selectPrjgroupByDeptId(deptId);
        return prjgroups;
    }


}